package com.light.gulimall.ware.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.light.common.enums.WareStatusEnum;
import com.light.common.utils.PageUtils;
import com.light.common.utils.Query;
import com.light.common.utils.R;
import com.light.gulimall.ware.dao.PurchaseDao;
import com.light.gulimall.ware.dao.PurchaseDetailDao;
import com.light.gulimall.ware.dao.WareSkuDao;
import com.light.gulimall.ware.dto.Item;
import com.light.gulimall.ware.dto.PurchaseDoneDTO;
import com.light.gulimall.ware.dto.PurchaseMergeDTO;
import com.light.gulimall.ware.entity.PurchaseDetailEntity;
import com.light.gulimall.ware.entity.PurchaseEntity;
import com.light.gulimall.ware.entity.WareSkuEntity;
import com.light.gulimall.ware.service.PurchaseService;
import com.light.gulimall.ware.service.WareSkuService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    /**
     * wms_purchase_detail
     */
    @Autowired
    private PurchaseDetailDao purchaseDetailDao;

    /**
     * wms_ware_sku 商品库存
     */
    @Autowired
    private WareSkuDao wareSkuDao;

    /**
     * 库存
     */
    @Autowired
    private WareSkuService wareSkuService;



    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 查询未领取的采购单
     *
     * @return 分页查询结果
     */
    @Override
    public PageUtils getUnreceiveList(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> purchaseEntityQueryWrapper = new QueryWrapper<>();
        purchaseEntityQueryWrapper.and((w) -> {
            w.eq("status", 1).or().eq("status", 0);
        });
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                purchaseEntityQueryWrapper
        );

        return new PageUtils(page);
    }

    /**
     * 合并采购需求
     * @param dto 前端传递参数
     * @return 是否成功
     */
    @Override
    public R merge(PurchaseMergeDTO dto) {
        //如果传递的purchaseId需要先创建一个整单
        Long purchaseId = dto.getPurchaseId();
        if (purchaseId == null) {
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(1);
            purchaseEntity.setCreateTime(new Date());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }
        //无论是否要创建整单，都需要合并，向wms_purchase_detail表中更新purchase_id
        for (Long item : dto.getItems()) {
            QueryWrapper<PurchaseDetailEntity> purchaseDetailEntityQueryWrapper = new QueryWrapper<>();
            purchaseDetailEntityQueryWrapper.eq("id", item);
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setStatus(1);
            purchaseDetailEntity.setPurchaseId(purchaseId);
            purchaseDetailDao.update(purchaseDetailEntity, purchaseDetailEntityQueryWrapper);
        }
        return R.ok();
    }

    /**
     * 领取采购单
     * @param ids 前端传递参数
     * @return 是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R receive(List<Long> ids) {

        //根据采购单id查询 wms_purchase_detail 表
        QueryWrapper<PurchaseDetailEntity> purchaseDetailEntityQueryWrapper = new QueryWrapper<>();
        purchaseDetailEntityQueryWrapper.in("purchase_id", ids);
        List<PurchaseDetailEntity> purchaseDetailEntities = purchaseDetailDao.selectList(purchaseDetailEntityQueryWrapper);

        //筛选出状态是 1-已领取的
        List<PurchaseDetailEntity> detailEntities = purchaseDetailEntities.stream().
                filter(purchaseDetailEntity -> purchaseDetailEntity.getStatus() == WareStatusEnum.ASSIGNED.getCode()).collect(Collectors.toList());

        //批量修改他们的状态为2-正在采购
        for (PurchaseDetailEntity detailEntity : detailEntities) {
            detailEntity.setStatus(WareStatusEnum.RECEIVE.getCode());
            purchaseDetailDao.update(detailEntity, new QueryWrapper<PurchaseDetailEntity>().eq("id", detailEntity.getId()));
        }

        //修改wms_purchase状态为2-正在采购
        List<PurchaseEntity> purchaseEntities = this.listByIds(ids);
        //筛选出状态是 1-已领取的
        List<PurchaseEntity> purchaseEntityList = purchaseEntities.stream().
                filter(purchaseEntity -> purchaseEntity.getStatus() == WareStatusEnum.ASSIGNED.getCode()).
                collect(Collectors.toList());
        for (PurchaseEntity purchaseEntity : purchaseEntityList) {
            purchaseEntity.setStatus(WareStatusEnum.RECEIVE.getCode());
        }
        this.updateBatchById(purchaseEntityList);
        return R.ok();
    }

    /**
     * 完成采购
     * @param dto 前端传递
     * @return 是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R receiveDone(PurchaseDoneDTO dto) {
        //采购单id
        Long id = dto.getId();

        List<Item> items = dto.getItems();
        //筛选出没有异常的采购需求
        List<Item> itemList = items.stream().filter(item -> item.getStatus().equals(WareStatusEnum.FINISH.getCode())).collect(Collectors.toList());
        //修改wms_purchase_detail表中没有异常的项目的状态为采购完成
        List<Long> itemIds = itemList.stream().map(Item::getItemId).collect(Collectors.toList());
        QueryWrapper<PurchaseDetailEntity> purchaseDetailEntityQueryWrapper = new QueryWrapper<>();
        purchaseDetailEntityQueryWrapper.in("id", itemIds);
        if (!CollectionUtils.isEmpty(itemList)) {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setStatus(WareStatusEnum.FINISH.getCode());
            purchaseDetailDao.update(purchaseDetailEntity, purchaseDetailEntityQueryWrapper);
            //新增或更新库存
            wareSkuService.addOrModitfy(itemIds);

        }



        //修改wms_purchase表的状态为采购完成
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);
        purchaseEntity.setStatus(WareStatusEnum.FINISH.getCode());
        updateById(purchaseEntity);



        return R.ok();
    }

}